﻿using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ECommerce.Controls
{
	public partial class CategoryNavigation : BaseUserControl
	{
		private Service.ICategoryService _CategoryService;

		public int CategoryID
		{
			get
			{
				return CommonHelper.QueryStringInt("categoryid");
			}
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			BindTopCategories();

			this.LCategoryNavigationCategoryMenuHeader.Text = GetLocalResourceString("CategoryNavigation.CategoryMenuHeader");
		}

		protected void RepeaterTopCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if (e.Item.DataItem != null)
			{
				string itemID = DataBinder.Eval(e.Item.DataItem, "CategoryID").ToString();
				int categoryID = 0;
				if (int.TryParse(itemID, out categoryID))
				{
					HyperLink hl = (HyperLink)e.Item.FindControl("HyperLinkTopCategory");

					hl.Text = DataBinder.Eval(e.Item.DataItem, "CategoryName").ToString().Trim();
					hl.NavigateUrl = "~/Category.aspx?categoryid=" + itemID;

					if (CategoryID.ToString() == itemID)
					{
						hl.CssClass = "categorymenubaractive";
					}

					if (_CategoryService == null)
					{
						_CategoryService = new Service.CategoryService();
					}

					var subCategories = _CategoryService.GetSubCategories(categoryID);

					Repeater r = (Repeater)e.Item.FindControl("RepeaterSubCategories");
					r.DataSource = subCategories;
					r.DataBind();
				}
			}
		}

		protected void RepeaterSubCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if (e.Item.DataItem != null)
			{
				string itemID = DataBinder.Eval(e.Item.DataItem, "CategoryID").ToString();
				HyperLink hl = (HyperLink)e.Item.FindControl("HyperLinkSubCategory");

				hl.Text = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + DataBinder.Eval(e.Item.DataItem, "CategoryName").ToString();
				hl.NavigateUrl = "~/Category.aspx?categoryid=" + itemID;

				if (CategoryID.ToString() == itemID)
				{
					hl.CssClass = "subcategorymenubaractive";
				}
			}
		}

		private void BindTopCategories()
		{
			if (SiteContext.Current == null)
			{
				Server.Transfer("~/HomePage.aspx");
			}

			if (SiteContext.Current.WorkingLanguage != null)
			{
				if (_CategoryService == null)
				{
					_CategoryService = new Service.CategoryService();
				}

				var category = _CategoryService.GetCategoryByLanguage(SiteContext.Current.WorkingLanguage.LanguageId);

				if (category != null)
				{
					var topCategories = (from tc in category
										 where tc.ParentCategoryID <= 0 && tc.Published
										 select tc);

					this.RepeaterTopCategories.DataSource = topCategories;
					this.RepeaterTopCategories.DataBind();
				}
				else
				{
					this.RepeaterTopCategories.DataSource = null;
					this.RepeaterTopCategories.DataBind();
				}
			}
		}
	}
}